package com.qkl.xiatang.app.utils;

import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.qkl.xiatang.app.dto.FeedQty;
import com.qkl.xiatang.app.dto.FeedQtyDTO;
import com.qkl.xiatang.app.dto.PageInDTO;
import com.qkl.xiatang.app.entity.user.AppUserInfo;
import com.qkl.xiatang.app.entity.BaseEntity;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.*;

public class AppUtils {

    private static SecureRandom RANDOM = new SecureRandom();

    private static DefaultIdentifierGenerator generator = null;

    static {
        InetAddress address = getInetAddress();
        if(null == address) {
            generator = new DefaultIdentifierGenerator();
        }else {
            generator = new DefaultIdentifierGenerator(address);
        }
    }

    public static Long genId(Object entity){
        return generator.nextId(entity);
    }

    public static String genIdStr(Object entity){
        Long id = genId(entity);
        if(null != id){
            return String.valueOf(id);
        }
        long currTime = System.currentTimeMillis();
        int ran = RANDOM.nextInt(10000);
        return String.valueOf(currTime) + ran;
    }

    public static String genIdStr(){
        return genIdStr(new HashMap<>());
    }

    /**
     * 获取本机IP
     */
    public static String getIp() {
        String ip = null;
        InetAddress address = getInetAddress();
        if(null != address){
            ip = address.getHostAddress();
        }
        return ip;
    }

    public static InetAddress getInetAddress(){
        try {
            return InetAddress.getLocalHost();

        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *阿里云签名id
     */
    public static final String ACCESS_KEY_ID = "LTAIN9hNTqSbPD49";


    /**
     * 调阿里云接口签名
     * @param value
     * @return
     */
    public static String getSign(String value){
        String signValue = ACCESS_KEY_ID + value;
        return DigestUtils.md5DigestAsHex((signValue).getBytes());
    }

    /**
     *
     * @param str ","号分隔的字符串
     * @return
     */
    public static List<String> stringToList(String str){
        List<String> idList = new ArrayList<>();
        String[]idArray = StringUtils.split(str,",");
        if(null != idArray && idArray.length > 0){
            for(String id : idArray){
                id = StringUtils.trimToEmpty(id);
                if(StringUtils.isEmpty(id)){
                    continue;
                }
                idList.add(id);
            }
        }
        return idList;
    }

    public static Integer parseInt(String s){
        if(StringUtils.isEmpty(s)){
            return null;
        }
        try{
            return Integer.parseInt(s);
        }catch (Exception e){
            return null;
        }
    }

    public static Double parseDouble(String s){
        if(StringUtils.isEmpty(s)){
            return null;
        }
        try{
            return Double.parseDouble(s);
        }catch (Exception e){
            return null;
        }
    }

    public static void toPageInDTO(Map<String,Object> webParams, PageInDTO pageInDTO){
        String pageIndex = StringUtils.trimToEmpty((String) webParams.get("pageIndex"));
        String pageSize = StringUtils.trimToEmpty((String) webParams.get("pageSize"));
        pageInDTO.setPageIndex(parseInt(pageIndex));
        pageInDTO.setPageSize(parseInt(pageSize));
    }

    public static Integer addInt(Integer ... ints){
        Integer total = 0;
        if(ObjectUtils.isNotEmpty(ints)){
            for(Integer i : ints){
                if(null == i){
                    continue;
                }
                total = total + i;
            }
        }
        return total;
    }

    public static String toURLParam(Map<String,Object> params){
        if(ObjectUtils.isEmpty(params)){
            return "";
        }
        StringBuffer sb = new StringBuffer();
        Set<Map.Entry<String, Object>> set = params.entrySet();
        for(Map.Entry<String, Object> entry :  set){
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        if(sb.length()  > 1){
            sb.deleteCharAt(sb.length()-1);
        }
        return sb.toString();
    }


    public static Date parseDate(String dateString,SimpleDateFormat format){
        if(StringUtils.isNotEmpty(dateString)) {
            try {
                Date d1 = format.parse(dateString);
                if (dateString.equals(format.format(d1))){
                    return d1;
                }
            } catch (Exception e) {
            }
        }
        return null;
    }

    public static String middleToDrop(String src){
        if(StringUtils.isAnyEmpty(src)){
            return src;
        }
        return src.replaceAll("-",".");
    }

    private static final String BASE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZOP0123456789";
    public static String randomChars(int len){
        int baseCharsLen = BASE_CHARS.length();
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<len;i++) {
            sb.append(BASE_CHARS.charAt(RANDOM.nextInt(baseCharsLen)));
        }
        return sb.toString();
    }

    public static String genNickname(){
        return "nickname_" + randomChars(8);
    }

    public static void setEntityInfo(BaseEntity entity){
        Date date = new Date();
        if(null == entity.getCreateTime()){
            entity.setCreateTime(date);
        }
        if(null == entity.getUpdateTime()){
            entity.setUpdateTime(date);
        }
        AppUserInfo user = AppSessionUtils.getSessionUser();
        if(StringUtils.isEmpty(entity.getCreateBy()) && null != user){
            entity.setCreateBy(user.getName());
        }
        if(StringUtils.isEmpty(entity.getUpdateBy()) && null != user){
            entity.setUpdateBy(user.getName());
        }
    }

    /**
     * 字符数组去重
     * @param strings
     * @return
     */
    public static List<String> stringsDistinct(List<String> strings){
        if(ObjectUtils.isEmpty(strings)){
            return new ArrayList<>();
        }
        List<String> retList = new ArrayList<>();
        Set<String> set = new HashSet<>();
        for(String str : strings){
            str = StringUtils.trimToEmpty(str);
            if(StringUtils.isEmpty(str)){
                continue;
            }
            if(set.contains(str)){
                continue;
            }
            set.add(str);
            retList.add(str);
        }
       return retList;
    }

    public static List<Integer> integersDistinct(List<Integer> integers){
        if(ObjectUtils.isEmpty(integers)){
            return new ArrayList<>();
        }
        List<Integer> integerList = new ArrayList<>();
        Set<Integer> set = new HashSet<>();
        for (Integer integer : integers){
            if(null == integer || set.contains(integer)){
                continue;
            }
            set.add(integer);
            integerList.add(integer);
        }
        return integerList;
    }

    public static String toYYYY_MM_DD(String date){
        if(StringUtils.isEmpty(date)){
            return date;
        }
        String[]arr = date.split("-");
        if(ObjectUtils.isEmpty(arr) || arr.length < 2){
            return date;
        }
        String year = arr[0];
        String month = arr[1];
        String day = arr[2];
        if(month.length()<2){
            month = "0" + month;
        }
        if(day.length()<2){
            day = "0" + day;
        }
        return year + "-" + month + "-" + day;
    }

    public static final String YYYY_MM_DD = "yyyy-MM-dd";

    /**
     *
     * @param date yyyy-MM-dd
     * @return
     */
    public static boolean checkYyyyMMdd(String date){
        SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
        try {
            return  date.equals(format.format(format.parse(date)));
        }catch (Exception e){
            return false;
        }
    }

    /**
     *
     * @param date yyyy-MM-dd
     * @return
     */
    public static Date yyyyMMddToDate(String date){
        SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
        try {
            return  format.parse(date);
        }catch (Exception e){
            return null;
        }
    }

    public static String toYyyyMMdd(Date date){
        if(null == date){
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
        return format.format(date);
    }

    public static String toYyyyMMddDrop(Date date){
        if(null == date){
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
        return format.format(date);
    }

    public static Date addHour(Date date,Integer hour){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.setTime(date);
        if(null != hour && hour > 0) {
            calendar.add(Calendar.HOUR, hour);
        }
        return calendar.getTime();
    }

    public static Date addDays(Date date,Integer days){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.setTime(date);
        if(null != days && days > 0) {
            calendar.add(Calendar.DATE, days);
        }
        return calendar.getTime();
    }

    public static Date todayYyyyMMdd(){
        SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
        try {
            return format.parse(format.format(new Date()));
        }catch (Exception e){
            return null;
        }
    }

    public static Date parseYyyyMMdd(String date){
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
        if(StringUtils.isNotEmpty(date)){
            try {
                return format.parse(date);
            }catch (Exception e){
            }
        }
        return null;

    }

    public static String yyyyMMdd(){
        SimpleDateFormat format = new SimpleDateFormat(YYYY_MM_DD);
        try {
            return format.format(new Date());
        }catch (Exception e){
            return null;
        }
    }

    public static Double addDouble(Double ... doubles){
        Double total = 0.0;
        for(Double d : doubles){
            if(null != d){
                total = total + d;
            }
        }
        return total;
    }

    public static List<FeedQty> sumFeedQty(List<? extends FeedQty> feedQtyList){
        Map<String,FeedQtyDTO> map = new HashMap<>();
        for(FeedQty feedQty : feedQtyList){
            if(!map.containsKey(feedQty.getFeedId())){
                map.put(feedQty.getFeedId(),new FeedQtyDTO(feedQty.getFeedId(),feedQty.getQty()));
                continue;
            }
            FeedQtyDTO qtyDTO = map.get(feedQty.getFeedId());
            qtyDTO.setQty(addDouble(qtyDTO.getQty(),feedQty.getQty()));
        }
        List<FeedQty> qtyList = new ArrayList<>();
        qtyList.addAll(map.values());
        return qtyList;
    }

    /**
     * 格式化金额
     * @param amt
     * @return
     */
    private static  final  String FORMAT_AMT = "%.2f";
    public  static Double formatAmt(Double amt){
        if(null != amt){
            return Double.parseDouble(String.format(FORMAT_AMT,amt));
        }
        return 0.0;
    }
    public static Double addAmt(Double ... amts){
        Double total = 0.0;
        if(ObjectUtils.isNotEmpty(amts)) {
            for (Double amt : amts) {
                if (null == amt) {
                    continue;
                }
                total = total + amt;
            }
        }
        return formatAmt(total);
    }

    public static Double multiplyAmt(Double ... doubles){
        Double total = null;
        if(ObjectUtils.isNotEmpty(doubles)) {
            for (Double amt : doubles) {
                if (null == amt || amt == 0) {
                    continue;
                }
                if(null == total){
                    total = 1.0;
                }
                total = total * amt;
            }
        }
        return formatAmt(total);
    }

    public static String toJavaName(String fieldName){
        String name = StringUtils.trimToEmpty(fieldName);
        if(StringUtils.isEmpty(name)){
            return name;
        }
        String[]stringArray = name.split("_");
        if(ObjectUtils.isEmpty(stringArray)){
            return name;
        }
        String result = stringArray[0];
        int len = stringArray.length;
        if(len < 2){
            return result;
        }
        for (int i = 1 ; i < len ; i++ ){
            String s = stringArray[i];
            if(StringUtils.isEmpty(s)){
                continue;
            }
            char[]chars = s.toCharArray();
            chars[0] = String.valueOf(chars[0]).toUpperCase().toCharArray()[0];
            result = result + new String(chars);
        }
       return result;
    }


    public static void main(String[] args) {

        System.out.println(toJavaName("ts"));


    }

}
